"""
日志记录模块
提供统一的日志记录功能
"""

import logging
import os
from pathlib import Path
from typing import Optional, Dict, Any


class Logger:
    """统一的日志记录器"""
    
    def __init__(self, name: str = "fmcw_radar", log_config: Optional[Dict[str, Any]] = None):
        """
        初始化日志记录器
        
        Args:
            name: 日志记录器名称
            log_config: 日志配置字典
        """
        self.name = name
        self.logger = logging.getLogger(name)
        
        # 默认配置
        default_config = {
            "level": "INFO",
            "file": "./logs/fmcw_radar.log",
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "date_format": "%Y-%m-%d %H:%M:%S"
        }
        
        # 使用提供的配置或默认配置
        config = log_config if log_config else default_config
        
        # 避免重复添加处理器
        if not self.logger.handlers:
            self._setup_logger(config)
    
    def _setup_logger(self, config: Dict[str, Any]) -> None:
        """
        设置日志记录器
        
        Args:
            config: 日志配置
        """
        # 设置日志级别
        level_str = config.get("level", "INFO").upper()
        self.logger.setLevel(getattr(logging, level_str, logging.INFO))
        
        # 创建格式化器
        formatter = logging.Formatter(
            config.get("format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"),
            datefmt=config.get("date_format", "%Y-%m-%d %H:%M:%S")
        )
        
        # 添加控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)
        
        # 添加文件处理器
        log_file = config.get("file", "./logs/fmcw_radar.log")
        if log_file:
            # 确保日志目录存在
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)
            
            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setLevel(getattr(logging, level_str, logging.INFO))
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)
        
        # 防止日志传播到根记录器
        self.logger.propagate = False
    
    def debug(self, message: str) -> None:
        """记录调试信息"""
        self.logger.debug(message)
    
    def info(self, message: str) -> None:
        """记录信息"""
        self.logger.info(message)
    
    def warning(self, message: str) -> None:
        """记录警告"""
        self.logger.warning(message)
    
    def error(self, message: str) -> None:
        """记录错误"""
        self.logger.error(message)
    
    def critical(self, message: str) -> None:
        """记录严重错误"""
        self.logger.critical(message)
    
    def exception(self, message: str) -> None:
        """记录异常（包含堆栈跟踪）"""
        self.logger.exception(message)


def setup_logger(log_config: Optional[Dict[str, Any]] = None, name: str = "fmcw_radar") -> Logger:
    """
    设置并返回日志记录器
    
    Args:
        log_config: 日志配置字典
        name: 日志记录器名称
        
    Returns:
        配置好的日志记录器实例
    """
    return Logger(name, log_config)


# 创建默认日志记录器实例
default_logger = Logger()